package com.studentManagement.utils;

import java.sql.*;

public class JdbcUtil {

    public static Connection getConnection() {
        Connection conn = null;
//        String url = "jdbc:mysql://127.0.0.1:3306/studentmanagement?"
//                + "user=root&password=root&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
        String url = "jdbc:mysql://119.29.201.149:3306/studentManagement?"
                + "user=root&password=TXyun-595726017&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
        try {
            Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动
            conn = DriverManager.getConnection(url);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return conn;
        }
    }

    //开启事务
    public static void beginTransaction(Connection conn) {
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //提交事务
    public static void commit(Connection conn) {
        try {
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //回滚事务
    public static void rollback(Connection conn) {
        try {
            conn.rollback();
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭连接
    public static void closeConnection(Connection conn) {

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭statement 和 resultset
    public static void closeStatementAndResultSet(ResultSet resultSet, Statement statement) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();

        }
    }
}